package com.nymph.session.impl;

import com.nymph.executor.Executor;
import com.nymph.executor.SimpleExecutor;
import com.nymph.mapping.MappedStatement;
import com.nymph.session.Configuration;
import com.nymph.session.SqlSession;
import com.nymph.util.CommonUtis;

import java.util.List;


/**
 * @Description: This is a sample class.
 * @Author: Simon
 */
public class DefaultSqlSession implements SqlSession {

    private final Configuration configuration;

    private final Executor executor;

    public DefaultSqlSession(Configuration configuration) {
        this.configuration = configuration;
        this.executor = new SimpleExecutor(configuration);
    }

    @Override
    public <T> T selectOne(String StatementId, Object parameter) {
        List<T> results = this.selectList(StatementId, parameter);
        return CommonUtis.isNotEmpty(results) ? results.get(0) : null;
    }

    @Override
    public <E> List<E> selectList(String StatementId, Object parameter) {
        MappedStatement mappedStatement = this.configuration.getMappedStatement(StatementId);
        return this.executor.doQuery(mappedStatement,parameter);
    }

    @Override
    public void update(String StatementId, Object parameter) {
        MappedStatement mappedStatement = this.configuration.getMappedStatement(StatementId);
        this.executor.doUpdate(mappedStatement,parameter);
    }

    @Override
    public void insert(String statementId, Object parameter) {
        // todo
    }

    @Override
    public <T> T getMapper(Class<T> type) {
        return configuration.getMapper(type,this);
    }

    @Override
    public Configuration getConfiguration() {
        return this.configuration;
    }

}
